import GROUP_DATA from '../../utils/groups.js'
import storage from '../../utils/storage.js'

Page({
  data: {
    currentWordIndex: 0,
    words: [],
    groupId: null,
    groupName: '',
    isLastWord: false,
    groupProgress: null,
    isPlaying: false,
    currentAudioContext: null,
    settings: {
      showChineseSentence: true,
      playEnglishSentence: false,
      playChineseSentence: false
    }
  },

  onLoad(options) {
    const { groupId } = options;
    
    // 获取分组单词数据
    const groupData = GROUP_DATA.find(item => item.group.group_id === groupId);
    if (!groupData) return;
    
    // 获取该分组的学习进度
    const groupProgress = storage.getGroupProgress(groupId);
    let startIndex = 0;

    if (groupProgress && groupProgress.lastWordId) {
      // 如果有学习进度，从上次学习的单词开始
      startIndex = groupData.words.findIndex(word => 
        word.word_id === groupProgress.lastWordId
      );
      startIndex = startIndex === -1 ? 0 : startIndex;
    }

    // 加载设置
    const settings = wx.getStorageSync('settings') || {
      showChineseSentence: true,
      playEnglishSentence: false,
      playChineseSentence: false
    };
    
    this.setData({
      words: groupData.words,
      groupId,
      groupName: groupData.group.word_chinese,
      currentWordIndex: startIndex,
      groupProgress: groupProgress || {
        isCompleted: false
      },
      isLastWord: startIndex === groupData.words.length - 1,
      settings
    }, () => {
      // 自动播放当前单词的音频
      this.playCurrentWordAudio();
    });

    // 更新当前学习进度
    this.updateLearningProgress();
  },

  // 播放当前单词的所有音频
  playCurrentWordAudio() {
    const { currentWordIndex, words } = this.data;
    const word = words[currentWordIndex];
    const settings = wx.getStorageSync('settings') || {
      playEnglishSentence: false,
      playChineseSentence: false
    };
    
    // 基础音频列表
    const audioList = [
      word.word_english_audio,
      word.word_chinese_audio,
      word.word_english_audio,
    ];

    // 根据设置添加句子音频
    if (settings.playEnglishSentence) {
      audioList.push(word.sentence_english_audio);
    }
    if (settings.playChineseSentence) {
      audioList.push(word.sentence_chinese_audio);
    }

    console.log('audioList', audioList)
    this.playAudioSequentially(audioList, 0);
  },

  // 顺序播放音频列表
  playAudioSequentially(audioList, index) {
    if (index >= audioList.length) {
      this.setData({ isPlaying: false });
      return;
    }

    // 如果已经有正在播放的音频，先停止
    // if (this.data.currentAudioContext) {
    //   this.data.currentAudioContext.destroy();
    // }

    const audioContext = wx.createInnerAudioContext();
    audioContext.src = audioList[index];
    
    this.setData({
      currentAudioContext: audioContext,
      isPlaying: true
    });

    audioContext.onEnded(() => {
      audioContext.destroy();
      this.playAudioSequentially(audioList, index + 1);
    });
    
    audioContext.onError(() => {
      console.error('音频播放失败:', audioList[index]);
      audioContext.destroy();
      this.playAudioSequentially(audioList, index + 1);
    });
    
    audioContext.play();
  },

  // 手动播放单词音频
  playWordAudio() {
    // 如果正在播放，不响应点击
    if (this.data.isPlaying) return;
    
    const { currentWordIndex, words } = this.data;
    const word = words[currentWordIndex];
    
    if (!word) {
      console.error('当前单词数据无效');
      return;
    }

    const settings = wx.getStorageSync('settings') || {
      playEnglishSentence: false,
      playChineseSentence: false
    };

    // 基础音频列表
    const audioList = [
      word.word_english_audio,
      word.word_chinese_audio,
      word.word_english_audio,
    ];

    // 根据设置添加句子音频
    if (settings.playEnglishSentence) {
      audioList.push(word.sentence_english_audio);
    }
    if (settings.playChineseSentence) {
      audioList.push(word.sentence_chinese_audio);
    }

    console.log('audioList', audioList)
    this.playAudioSequentially(audioList, 0);
  },

  // 处理滑动切换
  handleSwiperChange(e) {
    const current = e.detail.current;
    
    // 如果正在播放音频，先停止
    if (this.data.isPlaying && this.data.currentAudioContext) {
      this.data.currentAudioContext.destroy();
      this.setData({ 
        isPlaying: false,
        currentAudioContext: null
      });
    }

    this.setData({
      currentWordIndex: current,
      isLastWord: current === this.data.words.length - 1
    });
    
    // 更新学习进度
    this.updateLearningProgress();
    // 自动播放当前单词音频
    this.playCurrentWordAudio();
  },

  // 前往测试页面
  goToTest() {
    if (!this.data.isLastWord && !this.data.groupProgress.isCompleted) return;
    
    wx.navigateTo({
      url: `/pages/testSelection/testSelection?groupId=${this.data.groupId}`
    });
  },

  // 更新学习进度
  updateLearningProgress() {
    const { groupId, words, currentWordIndex, isLastWord } = this.data;
    
    if (isLastWord) {
      // 如果是最后一个单词，标记分组为已完成
      storage.setGroupCompleted(groupId, this.data.groupName);
    } else {
      storage.updateGroupProgress(groupId, {
        lastWordId: words[currentWordIndex].word_id
      });
    }
  },

  // 页面卸载时清理音频
  onUnload() {
    console.log('onUnload')
    // 停止所有背景音频
    const audioContexts = wx.getBackgroundAudioManager();
    if (audioContexts) {
      audioContexts.stop();
    }

    // 停止所有 InnerAudioContext
    const innerAudioContext = wx.createInnerAudioContext();
    if (innerAudioContext) {
      innerAudioContext.stop();
    }

    // 如果页面中有存储的音频上下文，也要清理
    if (this.data.currentAudioContext) {
      this.data.currentAudioContext && this.data.currentAudioContext.destroy();
      this.setData({
        currentAudioContext: null,
        isPlaying: false
      });
    }
  },

  // 在现有代码中添加 onHide 生命周期函数
  onHide() {
    console.log('onHide - stopping audio');
    // 停止所有背景音频
    const audioContexts = wx.getBackgroundAudioManager();
    if (audioContexts) {
      audioContexts.stop();
    }

    // 停止所有 InnerAudioContext
    const innerAudioContext = wx.createInnerAudioContext();
    if (innerAudioContext) {
      innerAudioContext.stop();
    }

    // 如果页面中有存储的音频上下文，也要清理
    if (this.data.currentAudioContext) {
      this.data.currentAudioContext && this.data.currentAudioContext.destroy();
      this.setData({
        currentAudioContext: null,
        isPlaying: false
      });
    }
  },

  // 在现有方法之后添加
  goToSettings() {
    wx.navigateTo({
      url: '/pages/settings/settings'
    });
  },

  // 在现有代码中添加或修改 onShow 函数
  onShow: function() {
    // 获取最新的设置配置
    const settings = wx.getStorageSync('settings') || {
      showChineseSentence: true,
      // 其他设置项...
    };
    
    this.setData({
      settings: settings
    });
  }
}); 